package com.example.music

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.ImageButton
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager2.widget.ViewPager2
import com.example.music.data.PlaybackState
import com.example.music.ui.adapters.MainPagerAdapter
import com.example.music.viewmodel.MusicViewModel

class MainActivity : AppCompatActivity() {
    
    private lateinit var viewModel: MusicViewModel
    private lateinit var viewPager: ViewPager2
    private lateinit var bottomNavigation: LinearLayout
    private lateinit var bottomPlayerCard: LinearLayout
    private lateinit var currentSongTitle: TextView
    private lateinit var currentSongArtist: TextView
    private lateinit var playPauseButton: ImageButton
    
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        if (!allGranted) {
            // Handle permission denied
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        setupToolbar()
        setupViews()
        setupViewModel()
        setupViewPager()
        setupBottomNavigation()
        setupBottomPlayer()
        requestPermissions()
    }
    
    private fun setupToolbar() {
        val toolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.title = "音乐播放器"
    }
    
    private fun setupViews() {
        viewPager = findViewById(R.id.viewPager)
        bottomNavigation = findViewById(R.id.bottomNavigation)
        bottomPlayerCard = findViewById(R.id.bottomPlayerCard)
        currentSongTitle = findViewById(R.id.currentSongTitle)
        currentSongArtist = findViewById(R.id.currentSongArtist)
        playPauseButton = findViewById(R.id.playPauseButton)
    }
    
    private fun setupViewModel() {
        viewModel = ViewModelProvider(this)[MusicViewModel::class.java]
        
        viewModel.currentMusic.observe(this) { music ->
            if (music != null) {
                bottomPlayerCard.visibility = View.VISIBLE
                currentSongTitle.text = music.title
                currentSongArtist.text = music.artist ?: "未知艺术家"
            } else {
                bottomPlayerCard.visibility = View.GONE
            }
        }
        
        viewModel.playbackState.observe(this, Observer { state ->
            when (state) {
                PlaybackState.PLAYING -> {
                    playPauseButton.setImageResource(R.drawable.ic_pause)
                }
                else -> {
                    playPauseButton.setImageResource(R.drawable.ic_play_arrow)
                }
            }
        })
    }
    
    private fun setupViewPager() {
        val adapter = MainPagerAdapter(this)
        viewPager.adapter = adapter
        viewPager.isUserInputEnabled = false // 禁用滑动切换
    }
    
    private fun setupBottomNavigation() {
        findViewById<Button>(R.id.nav_home).setOnClickListener {
            viewPager.currentItem = 0
        }
        findViewById<Button>(R.id.nav_library).setOnClickListener {
            viewPager.currentItem = 1
        }
        findViewById<Button>(R.id.nav_search).setOnClickListener {
            viewPager.currentItem = 2
        }
        findViewById<Button>(R.id.nav_profile).setOnClickListener {
            viewPager.currentItem = 3
        }
    }
    
    private fun setupBottomPlayer() {
        playPauseButton.setOnClickListener {
            if (viewModel.playbackState.value == PlaybackState.PLAYING) {
                viewModel.pause()
            } else {
                viewModel.play()
            }
        }
        
        bottomPlayerCard.setOnClickListener {
            // TODO: 展开全屏播放器
        }
    }
    
    private fun requestPermissions() {
        val permissions = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_MEDIA_AUDIO
        )
        
        val permissionsToRequest = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }
        
        if (permissionsToRequest.isNotEmpty()) {
            requestPermissionLauncher.launch(permissionsToRequest.toTypedArray())
        }
    }
}